﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;

using BLL;
using DAL;
using Models;
using System.Data;
using System.Text;
using System.Xml;
using Gift.WebApp;

public partial class backstage_goods_list : System.Web.UI.Page
{
    // Fields
    protected AdminGroupManager agm = new AdminGroupManager();

    protected CategoryManager cm = new CategoryManager();

    protected GoodsCategoryManager gcm = new GoodsCategoryManager();
    protected GoodsEntitysManager gem = new GoodsEntitysManager();
    protected GoodGalleryManager ggm = new GoodGalleryManager();
    protected GoodsManager gm = new GoodsManager();

    protected string kw = "";
    protected string order = "id";
    protected int ot = 1;
    protected int pageCount = 0;
    protected int pageIndex = 1;
    protected int pageSize = 20;
    protected PageList pl = new PageList();
    protected PageListManager plm = new PageListManager();
    protected int t = 0;
    protected int total = 0;

    // Methods
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        DataTable goodGalleryByGoods;
        string pathAndQuery = HttpContext.Current.Request.Url.PathAndQuery;
        string str2 = base.Request.Form["Item"];
        if (str2.Contains(","))
        {
            Array array = str2.Split(new char[] { ',' });
            foreach (string str3 in array)
            {
                goodGalleryByGoods = this.ggm.GetGoodGalleryByGoods(Convert.ToInt32(str3));
                if (this.gm.DeleteGoods(Convert.ToInt32(str3)))
                {
                    foreach (DataRow row in goodGalleryByGoods.Rows)
                    {
                        if ((row["thumbImg"].ToString() != "") && File.Exists(base.Server.MapPath(row["thumbImg"].ToString())))
                        {
                            File.Delete(base.Server.MapPath(row["thumbImg"].ToString()));
                        }
                        if ((row["smallImg"].ToString() != "") && File.Exists(base.Server.MapPath(row["smallImg"].ToString())))
                        {
                            File.Delete(base.Server.MapPath(row["smallImg"].ToString()));
                        }
                        if ((row["bigImg"].ToString() != "") && File.Exists(base.Server.MapPath(row["bigImg"].ToString())))
                        {
                            File.Delete(base.Server.MapPath(row["bigImg"].ToString()));
                        }
                    }
                }
            }
        }
        else
        {
            goodGalleryByGoods = this.ggm.GetGoodGalleryByGoods(Convert.ToInt32(str2));
            if (this.gm.DeleteGoods(Convert.ToInt32(str2)))
            {
                foreach (DataRow row in goodGalleryByGoods.Rows)
                {
                    if ((row["thumbImg"].ToString() != "") && File.Exists(base.Server.MapPath(row["thumbImg"].ToString())))
                    {
                        File.Delete(base.Server.MapPath(row["thumbImg"].ToString()));
                    }
                    if ((row["smallImg"].ToString() != "") && File.Exists(base.Server.MapPath(row["smallImg"].ToString())))
                    {
                        File.Delete(base.Server.MapPath(row["smallImg"].ToString()));
                    }
                    if ((row["bigImg"].ToString() != "") && File.Exists(base.Server.MapPath(row["bigImg"].ToString())))
                    {
                        File.Delete(base.Server.MapPath(row["bigImg"].ToString()));
                    }
                }
            }
        }
        base.Response.Redirect(pathAndQuery);
    }

    protected void btnExport_Click(object sender, EventArgs e)
    {
        try
        {
            string term = "";
            if ((base.Request.QueryString["t"] != null) && (base.Request.QueryString["kw"] != null))
            {
                this.kw = base.Request.QueryString["kw"];
                if (base.Request.QueryString["t"] != "categoryName")
                {
                    term = base.Request.QueryString["t"] + " like '%" + this.kw + "%' and languageVersion='" + this.Session["language_version"].ToString() + "'";
                }
                else
                {
                    term = "tb_goods.id in(select goods from tb_goodsCategory a left join tb_category b on a.category=b.categoryIdentity where b.categoryName like '%" + this.kw + "%') and languageVersion='" + this.Session["language_version"].ToString() + "'";
                }
            }
            else
            {
                term = "languageVersion='" + this.Session["language_version"].ToString() + "'";
            }
            ExcelHelper.ExportDataTableToExcel(this.gm.GetAllGoodsByTerm(term), DateTime.Now.ToString("yyyyMMddHHmmssffffff") + ".xls", "商品列表");
        }
        catch
        {
        }
    }

    protected void btnImport_Click(object sender, EventArgs e)
    {
        try
        {
            string filename = base.Server.MapPath("/cn/excel/" + DateTime.Now.ToString("yyyyMMddHHmmssffffff") + Path.GetExtension(this.fileExcel.PostedFile.FileName));
            this.fileExcel.PostedFile.SaveAs(filename);
            DataTable table = ExcelHelper.ImportDataTableFromExcel(filename, "商品列表", 0);
            ArrayList list = new ArrayList();
            int num = 0;
            int id = 0;
            foreach (DataRow row in table.Rows)
            {
                GoodsCategory category;
                GoodsEntitys entitys;
                Goods goods = new Goods();
                if (row["商品序号"].ToString() != "")
                {
                    goods.Id = Convert.ToInt32(row["商品序号"]);
                    if ((((((row["商品分类"].ToString() != "") && (row["品牌"].ToString() != "")) && ((row["是否精品"].ToString() != "") && (row["是否新品"].ToString() != ""))) && (((row["是否上架"].ToString() != "") && (row["是否热销"].ToString() != "")) && ((row["是否打折促销"].ToString() != "") && (row["是否参与会员打折"].ToString() != "")))) && ((((row["是否订单满额免运费"].ToString() != "") && (row["是否订单满额打折"].ToString() != "")) && ((row["是否订单满额减少"].ToString() != "") && (row["是否订单满额赠送礼品"].ToString() != ""))) && ((row["是否订单满额赠送积分"].ToString() != "") && (row["是否免运费"].ToString() != "")))) && (row["运费模版"].ToString() != ""))
                    {
                        goods.CategoryId = row["商品分类"].ToString();
                        goods.Brand = Convert.ToInt32(row["品牌"]);
                        goods.GoodsName = row["商品名称"].ToString();
                        goods.GoodsNo = row["商品编号"].ToString();
                        goods.Origin = row["产地"].ToString();
                        goods.IsBest = Convert.ToInt32(row["是否精品"]);
                        goods.IsNew = Convert.ToInt32(row["是否新品"]);
                        goods.IsTopSelling = Convert.ToInt32(row["是否上架"]);
                        goods.IsShelves = Convert.ToInt32(row["是否热销"]);
                        goods.IsPromote = Convert.ToInt32(row["是否打折促销"]);
                        goods.IsUserDiscount = Convert.ToInt32(row["是否参与会员打折"]);
                        goods.IsOrderFromFreight = Convert.ToInt32(row["是否订单满额免运费"]);
                        goods.IsDiscount = Convert.ToInt32(row["是否订单满额打折"]);
                        goods.IsTotalReduce = Convert.ToInt32(row["是否订单满额减少"]);
                        goods.IsGifts = Convert.ToInt32(row["是否订单满额赠送礼品"]);
                        goods.IsSendIntegral = Convert.ToInt32(row["是否订单满额赠送积分"]);
                        goods.IsFromFreight = Convert.ToInt32(row["是否免运费"]);
                        goods.FreightTemplate = Convert.ToInt32(row["运费模版"]);
                        DataTable goodsById = this.gm.GetGoodsById(goods.Id);
                        if (goodsById.Rows.Count > 0)
                        {
                            DataRow row2 = goodsById.Rows[0];
                            goods.GoodsType = Convert.ToInt32(row2["goodsType"]);
                            goods.Keywords = row2["keywords"].ToString();
                            goods.Description = row2["description"].ToString();
                            goods.GoodsRemark = row2["goodsRemark"].ToString();
                            if (this.gm.ModifyGoods(goods))
                            {
                                num++;
                                ArrayList list2 = ArrayList.Adapter(goods.CategoryId.Split(new char[] { ',' }));
                                ArrayList list3 = new ArrayList();
                                DataTable goodsCategoryByGoods = this.gcm.GetGoodsCategoryByGoods(goods.Id);
                                category = new GoodsCategory();
                                category.Goods = goods.Id;
                                foreach (DataRow row3 in goodsCategoryByGoods.Rows)
                                {
                                    list3.Add(row3["category"].ToString());
                                    if (!list2.Contains(row3["category"].ToString()))
                                    {
                                        this.gcm.DeleteGoodsCategory(Convert.ToInt32(row3["id"]));
                                    }
                                }
                                foreach (string str2 in list2)
                                {
                                    if (!list3.Contains(str2))
                                    {
                                        category.Category = Convert.ToInt32(str2);
                                        this.gcm.AddGoodsCategory(category);
                                    }
                                }
                            }
                        }
                        entitys = new GoodsEntitys();
                        entitys.Goods = goods.Id;
                        entitys.BarCode = row["商品条形码"].ToString();
                        entitys.GoodsArtno = row["商品货号"].ToString();
                        entitys.SalePrice = Convert.ToDecimal(row["销售价格"]);
                        entitys.MarketPrice = Convert.ToDecimal(row["市场价格"]);
                        entitys.CostPrice = Convert.ToDecimal(row["成本价格"]);
                        entitys.GiveIntegral = Convert.ToInt32(row["购买商品赠送积分"]);
                        entitys.GoodsWeight = Convert.ToDecimal(row["重量"]);
                        entitys.WeightUnit = row["单位"].ToString();
                        entitys.Integral = 0;
                        entitys.Inventory = Convert.ToInt32(row["库存"]);
                        if (row["销售序号"].ToString() != "")
                        {
                            entitys.Id = Convert.ToInt32(row["销售序号"]);
                            this.gem.ModifyGoodsEntitys(entitys);
                        }
                        else
                        {
                            this.gem.AddGoodsEntitys(entitys);
                        }
                    }
                    else
                    {
                        entitys = new GoodsEntitys();
                        entitys.Goods = goods.Id;
                        entitys.BarCode = row["商品条形码"].ToString();
                        entitys.GoodsArtno = row["商品货号"].ToString();
                        entitys.SalePrice = Convert.ToDecimal(row["销售价格"]);
                        entitys.MarketPrice = Convert.ToDecimal(row["市场价格"]);
                        entitys.CostPrice = Convert.ToDecimal(row["成本价格"]);
                        entitys.GiveIntegral = Convert.ToInt32(row["购买商品赠送积分"]);
                        entitys.GoodsWeight = Convert.ToDecimal(row["重量"]);
                        entitys.WeightUnit = row["单位"].ToString();
                        entitys.Integral = 0;
                        entitys.Inventory = Convert.ToInt32(row["库存"]);
                        if (row["销售序号"].ToString() != "")
                        {
                            entitys.Id = Convert.ToInt32(row["销售序号"]);
                            this.gem.ModifyGoodsEntitys(entitys);
                        }
                        else
                        {
                            this.gem.AddGoodsEntitys(entitys);
                        }
                    }
                }
                else if ((((((row["商品分类"].ToString() != "") && (row["品牌"].ToString() != "")) && ((row["是否精品"].ToString() != "") && (row["是否新品"].ToString() != ""))) && (((row["是否上架"].ToString() != "") && (row["是否热销"].ToString() != "")) && ((row["是否打折促销"].ToString() != "") && (row["是否参与会员打折"].ToString() != "")))) && ((((row["是否订单满额免运费"].ToString() != "") && (row["是否订单满额打折"].ToString() != "")) && ((row["是否订单满额减少"].ToString() != "") && (row["是否订单满额赠送礼品"].ToString() != ""))) && ((row["是否订单满额赠送积分"].ToString() != "") && (row["是否免运费"].ToString() != "")))) && (row["运费模版"].ToString() != ""))
                {
                    goods.CategoryId = row["商品分类"].ToString();
                    goods.Brand = Convert.ToInt32(row["品牌"]);
                    goods.GoodsName = row["商品名称"].ToString();
                    goods.GoodsNo = row["商品编号"].ToString();
                    goods.Origin = row["产地"].ToString();
                    goods.IsBest = Convert.ToInt32(row["是否精品"]);
                    goods.IsNew = Convert.ToInt32(row["是否新品"]);
                    goods.IsTopSelling = Convert.ToInt32(row["是否上架"]);
                    goods.IsShelves = Convert.ToInt32(row["是否热销"]);
                    goods.IsPromote = Convert.ToInt32(row["是否打折促销"]);
                    goods.IsUserDiscount = Convert.ToInt32(row["是否参与会员打折"]);
                    goods.IsOrderFromFreight = Convert.ToInt32(row["是否订单满额免运费"]);
                    goods.IsDiscount = Convert.ToInt32(row["是否订单满额打折"]);
                    goods.IsTotalReduce = Convert.ToInt32(row["是否订单满额减少"]);
                    goods.IsGifts = Convert.ToInt32(row["是否订单满额赠送礼品"]);
                    goods.IsSendIntegral = Convert.ToInt32(row["是否订单满额赠送积分"]);
                    goods.IsFromFreight = Convert.ToInt32(row["是否免运费"]);
                    goods.FreightTemplate = Convert.ToInt32(row["运费模版"]);
                    goods.GoodsType = 0;
                    goods.Keywords = "";
                    goods.Description = "";
                    goods.GoodsRemark = "";
                    Admin admin = this.Session["admin_user"] as Admin;
                    goods.Creator = admin.Id;
                    goods.LanguageVersion = this.Session["language_version"].ToString();
                    goods.Id = this.gm.AddGoods(goods);
                    if (goods.Id != 0)
                    {
                        id = goods.Id;
                        num++;
                        Array array = goods.CategoryId.Split(new char[] { ',' });
                        category = new GoodsCategory();
                        foreach (string str2 in array)
                        {
                            category.Goods = goods.Id;
                            category.Category = Convert.ToInt32(str2);
                            this.gcm.AddGoodsCategory(category);
                        }
                    }
                    entitys = new GoodsEntitys();
                    entitys.Goods = goods.Id;
                    entitys.BarCode = row["商品条形码"].ToString();
                    entitys.GoodsArtno = row["商品货号"].ToString();
                    entitys.SalePrice = Convert.ToDecimal(row["销售价格"]);
                    entitys.MarketPrice = Convert.ToDecimal(row["市场价格"]);
                    entitys.CostPrice = Convert.ToDecimal(row["成本价格"]);
                    entitys.GiveIntegral = Convert.ToInt32(row["购买商品赠送积分"]);
                    entitys.GoodsWeight = Convert.ToDecimal(row["重量"]);
                    entitys.WeightUnit = row["单位"].ToString();
                    entitys.Integral = 0;
                    entitys.Inventory = Convert.ToInt32(row["库存"]);
                    this.gem.AddGoodsEntitys(entitys);
                }
                else
                {
                    entitys = new GoodsEntitys();
                    entitys.Goods = id;
                    entitys.BarCode = row["商品条形码"].ToString();
                    entitys.GoodsArtno = row["商品货号"].ToString();
                    entitys.SalePrice = Convert.ToDecimal(row["销售价格"]);
                    entitys.MarketPrice = Convert.ToDecimal(row["市场价格"]);
                    entitys.CostPrice = Convert.ToDecimal(row["成本价格"]);
                    entitys.GiveIntegral = Convert.ToInt32(row["购买商品赠送积分"]);
                    entitys.GoodsWeight = Convert.ToDecimal(row["重量"]);
                    entitys.WeightUnit = row["单位"].ToString();
                    entitys.Integral = 0;
                    entitys.Inventory = Convert.ToInt32(row["库存"]);
                    this.gem.AddGoodsEntitys(entitys);
                }
            }
            if (File.Exists(filename))
            {
                File.Delete(filename);
            }
            base.ClientScript.RegisterStartupScript(base.GetType(), "message", "<script language=\"javascript\" defer>alert(\"更新成功,共更新" + num + "条商品信息！\");location.href=\"goods_list.aspx\";</script>");
        }
        catch
        {
        }
    }

    protected string GetCategoryName(object category)
    {
        string str = "";
        try
        {
            ArrayList list = ArrayList.Adapter(category.ToString().Split(new char[] { ',' }));
            for (int i = 0; i < list.Count; i++)
            {
                DataTable categoryByCategoryIdentity = this.cm.GetCategoryByCategoryIdentity(Convert.ToInt32(list[i]));
                str = str + ((i == 0) ? categoryByCategoryIdentity.Rows[0]["categoryName"].ToString() : ("," + categoryByCategoryIdentity.Rows[0]["categoryName"].ToString()));
            }
        }
        catch
        {
        }
        return str;
    }

    private void GoodsBind()
    {
        try
        {
            if (base.Request.QueryString["p"] != null)
            {
                this.pageIndex = int.Parse(base.Request.QueryString["p"]);
            }
            if (base.Request.QueryString["ps"] != null)
            {
                this.pageSize = Convert.ToInt32(base.Request.QueryString["ps"]);
            }
            if (base.Request.QueryString["or"] != null)
            {
                this.order = base.Request.QueryString["or"];
            }
            if (base.Request.QueryString["ot"] != null)
            {
                this.ot = Convert.ToInt32(base.Request.QueryString["ot"]);
            }
            this.pl.TblName = "view_goods";
            this.pl.StrGetFields = "id,goodsName,goodsNo,category,salePrice,isShelves,isBest,isNew,isTopSelling,inventory,isFromFreight";
            this.pl.FldName = this.order;
            this.pl.PageSize = this.pageSize;
            this.pl.PageIndex = this.pageIndex;
            this.pl.DoCount = 1;
            this.pl.OrderType = this.ot;
            if ((base.Request.QueryString["t"] != null) && (base.Request.QueryString["kw"] != null))
            {
                this.kw = base.Request.QueryString["kw"];
                if (base.Request.QueryString["t"] != "categoryName")
                {
                    this.pl.StrWhere = base.Request.QueryString["t"] + " like '%" + this.kw + "%' and languageVersion='" + this.Session["language_version"].ToString() + "'";
                }
                else
                {
                    this.pl.StrWhere = "id in(select goods from tb_goodsCategory a left join tb_category b on a.category=b.categoryIdentity where b.categoryName like '%" + this.kw + "%') and languageVersion='" + this.Session["language_version"].ToString() + "'";
                }
            }
            else
            {
                this.pl.StrWhere = "languageVersion='" + this.Session["language_version"].ToString() + "'";
            }
            Admin admin = this.Session["admin_user"] as Admin;
            DataTable adminGroupById = this.agm.GetAdminGroupById(admin.GroupId);
            if ((adminGroupById.Rows.Count > 0) && (Convert.ToInt32(adminGroupById.Rows[0]["isSupplier"]) == 1))
            {
                this.pl.StrWhere = this.pl.StrWhere + " and creator=" + admin.Id;
            }
            this.total = Convert.ToInt32(this.plm.GetPageList(this.pl).Rows[0]["Total"]);
            this.pl.DoCount = 0;
            DataTable pageList = this.plm.GetPageList(this.pl);
            new PageListNo().DelPageSize(pageList, this.total);
            if (pageList.Rows.Count == 0)
            {
                this.btnDelete.Visible = false;
            }
            this.rptGoods.DataSource = pageList.DefaultView;
            this.rptGoods.DataBind();
        }
        catch
        {
        }
    }

    protected override object LoadPageStateFromPersistenceMedium()
    {
        byte[] inArray = ViewStateCompression.DeCompress(Convert.FromBase64String(base.Request.Form.Get("__MSPVSTATE")));
        LosFormatter formatter = new LosFormatter();
        return formatter.Deserialize(Convert.ToBase64String(inArray));
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if ((HttpContext.Current.Session["admin_user"] == null) && (HttpContext.Current.Session["language_version"] == null))
        {
            base.ClientScript.RegisterStartupScript(base.GetType(), "sJs", "top.location=\"login.html\";", true);
        }
        if (!base.IsPostBack)
        {
            if (base.Request.QueryString["t"] != null)
            {
                base.ClientScript.RegisterStartupScript(base.GetType(), "sGs", "<script type=\"text/javascript\">selectIsExitItem(\"selectGoods\",\"" + base.Request.QueryString["t"] + "\");</script>");
            }
            if (base.Request.QueryString["ps"] != null)
            {
                base.ClientScript.RegisterStartupScript(base.GetType(), "sPs", "<script type=\"text/javascript\">selectIsExitItem(\"selectPageSize\",\"" + base.Request.QueryString["ps"] + "\");</script>");
            }
            this.btnDelete.Attributes.Add("disabled", "disabled");
            this.GoodsBind();
        }
    }

    protected void rptGoods_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        string pathAndQuery = HttpContext.Current.Request.Url.PathAndQuery;
        int goods = Convert.ToInt32(e.CommandArgument);
        if (e.CommandName == "del")
        {
            DataTable goodGalleryByGoods = this.ggm.GetGoodGalleryByGoods(goods);
            if (this.gm.DeleteGoods(goods))
            {
                foreach (DataRow row in goodGalleryByGoods.Rows)
                {
                    if ((row["thumbImg"].ToString() != "") && File.Exists(base.Server.MapPath(row["thumbImg"].ToString())))
                    {
                        File.Delete(base.Server.MapPath(row["thumbImg"].ToString()));
                    }
                    if ((row["smallImg"].ToString() != "") && File.Exists(base.Server.MapPath(row["smallImg"].ToString())))
                    {
                        File.Delete(base.Server.MapPath(row["smallImg"].ToString()));
                    }
                    if ((row["bigImg"].ToString() != "") && File.Exists(base.Server.MapPath(row["bigImg"].ToString())))
                    {
                        File.Delete(base.Server.MapPath(row["bigImg"].ToString()));
                    }
                }
                base.Response.Redirect(pathAndQuery);
            }
            else
            {
                base.ClientScript.RegisterStartupScript(base.GetType(), "sd", "<script language=\"javascript\" defer>alert('删除失败！');location.href='" + pathAndQuery + "';</script>");
            }
        }
    }

    protected override void SavePageStateToPersistenceMedium(object pViewState)
    {
        LosFormatter formatter = new LosFormatter();
        StringWriter output = new StringWriter();
        formatter.Serialize(output, pViewState);
        string hiddenFieldInitialValue = Convert.ToBase64String(ViewStateCompression.Compress(Convert.FromBase64String(output.ToString())));
        base.ClientScript.RegisterHiddenField("__MSPVSTATE", hiddenFieldInitialValue);
    }

}